#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>
#include <sys/wait.h>
#include <stdio.h>


int main(int argc, char **argv)
{
	char *p,*tmp;
	int fd,len,i;	
	pid_t pid;
		
	//fd = open("mymap",O_RDWR|O_CREAT|O_TRUNC,0664);
	fd = open("mymap",O_RDWR);	
	printf("%d\n",fd);
	ftruncate(fd,BUFSIZ);
	len = lseek(fd,0,SEEK_END);	
	printf("%d\n",len);

	p = (char *)mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	close(fd);//close is crucial		

	for(i = 0; i < 2; i++)
	{
		pid = fork();
		if(pid == 0)
		break;
	}
	
	if(i == 2)
	{
		munmap(p,len);
		wait(NULL);
		wait(NULL);
	}
	else if(i == 0)
	{
		tmp = p;
		for(i = 1; i < argc; i++)
		{			
			strcpy(tmp, argv[i]);
			tmp += sizeof(argv[i]);
			strcpy(tmp, " ");
			tmp += sizeof(" ");			
		}
		strcpy(tmp, "\n");
		munmap(p,len);
	}
	else
	{
		sleep(1);
		write(STDOUT_FILENO, p, len*sizeof(char));
		munmap(p,len);
	}
}
